package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    public final static String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录接口
     * @param userLoginDTO
     * @return
     */
    @Override
    public User Login(UserLoginDTO userLoginDTO) {
        //发送请求微信服务端并获取openid
        String openid = getOpenid(userLoginDTO.getCode());

        //判断openid是否为空，为空，抛异常
        if(openid==null)
        {
            throw  new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid获取user对象
        User user = userMapper.getByOpenId(openid);

        //如果user对象为空，则表示当前用户为新增用户，自动注册
        if(user==null)
        {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }

    //发送请求微信服务端并返回openid
    private String getOpenid(String code) {

        //设置map集合 配置文件
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(wxLoginUrl, map);   //获取返回的数据字符串

        //转换为json原始数据
        JSONObject jsonObject = JSON.parseObject(json);
        //根据键获取值
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
